﻿using LibGit2Sharp;
using LibGit2Sharp.Handlers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security;
using System.Text;

namespace MengCC.Core.Plugins
{
    public class GitDownloader
    {
        public bool Download(string storePath, string url,string branchName)
        {
            try
            {
                var userName = string.Empty;
                char[] pChar = string.Empty.ToCharArray();

                SecureString password = new SecureString();
                foreach (var item in pChar)
                {
                    password.AppendChar(item);
                }
                CredentialsHandler credentialsProvider = (_url, _user, _cred) => new SecureUsernamePasswordCredentials()
                {
                    Username = userName,
                    Password = password
                };

                if (!Directory.Exists(storePath) || Directory.GetFiles(storePath).Length == 0)
                {
                    Repository.Clone(url, storePath, new CloneOptions
                    {
                        CredentialsProvider = credentialsProvider,
                        BranchName = branchName
                    });
                }
                else
                {
                    using (var repo = new Repository(storePath))
                    {
                        FetchOptions fetchoptions = new FetchOptions();
                        fetchoptions.CredentialsProvider = credentialsProvider;
                        foreach (Remote remote in repo.Network.Remotes)
                        {
                            IEnumerable<string> refSpecs = remote.FetchRefSpecs.Select(x => x.Specification);
                            Commands.Pull(repo, new Signature(userName, userName, new DateTimeOffset(DateTime.Now)), new PullOptions { FetchOptions = fetchoptions });
                        }
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }
}
